package com.waypolice.common.utils;

import org.apache.commons.codec.binary.Base64;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Properties;


/**
 *String加解密
 * @author lzh
 *
 */
public class CheckUrlCodeUtil {

	private static Properties pro = ReadProperties.getProperties("key.properties");
	private static String pub_key_str = pro.getProperty("PUB_KEY_STR");
	private static String pri_key_str = pro.getProperty("PRI_KEY_STR");
	/**
	 * 使用MD5WithRSA的算法私钥进行加密(签名加密)
	 */

	public static String getMD5WithRSASign(String content) {
		Signature signature;
		byte[] signatureBytes;
		String sign;
		try {
			byte[] date = content.getBytes("UTF-8");
			byte[] priKeyBytes=pri_key_str.getBytes();
			byte[] keyBytes = Base64.decodeBase64(priKeyBytes);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
			signature = Signature.getInstance("MD5withRSA");
			signature.initSign(priKey);
			//date为要生成签名的数据字节数组
			signature.update(date);
			signatureBytes= signature.sign();
			sign=new String(Base64.encodeBase64(Base64.encodeBase64(signatureBytes)),"UTF-8");
			System.out.println(sign);
			return sign;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("getMD5WithRSASign算法异常！");
		}
	}
	/**
	 * 对用md5和RSA私钥生成的数字签名用公钥进行验证
	 * sign:getMD5WithRSASign加密方法生成的签名串
	 */

	public static boolean verifyWhenMD5WithRSASign(String sign,String content) {
		Signature signature;
		boolean flag = false;
		try {
			byte[] contentBytes = content.getBytes("utf-8");
			byte[] signBytes = sign.getBytes("utf-8");
			//对提供的公钥做base64解码
			byte[] pubKeyBytes = pub_key_str.getBytes();
			byte[] publickey = Base64.decodeBase64(pubKeyBytes);
			//签名需要二次解码
			signBytes = Base64.decodeBase64(Base64.decodeBase64(signBytes));
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publickey);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PublicKey pubKey = keyFactory.generatePublic(keySpec);
			signature = Signature.getInstance("MD5withRSA");
			signature.initVerify(pubKey);
			signature.update(contentBytes);
			flag = signature.verify(signBytes);
			System.out.println(flag);
		} catch (Exception e) {
			System.out.println("222");
			flag = false;
		}
		return flag;
	}
}
